
package com.scalar.chiptrack.marketing.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.io.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.calendar.Period;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.marketing.Pricing;
import com.scalar.chiptrack.marketing.parser.PriceSetupParser;
import com.scalar.chiptrack.marketing.dao.MarketingDAO;
import com.scalar.chiptrack.marketing.dao.PricingDAO;
import com.scalar.chiptrack.marketing.forms.PricingForm;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.ScalarException;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.4 $ $Date: 2007/07/31 05:55:19 $
 */

public final class PricingAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/priceSetting.do";
    String fileLocation     = null;
    // --------------------------------------------------------- Public Methods

	public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
        throws Exception
    {

        // Extract attributes and parameters we will need
        PricingForm subform = (PricingForm) form;
        String action = request.getParameter("action");
        //Get the session, to retrieve the values
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute (SessionKeys.USER_KEY);
        if ( user == null )
        {
            if( "loadCustomerPricing".equals ( action ) || "UpdateCustomerPricing".equals(action) )
            {
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?action=customerPricing" );
			}
            else if( "loadQuarterPricing".equals ( action ) || "UpdateQuarterPricing".equals(action) )
            {
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?action=quarterPricing" );
            }
            else if( "loadPricing".equals ( action ) )
            {
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?action=searchPricing" );
            }
            else
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
           return ( mapping.findForward ( "login" ) );

        }
        // Validate the request parameters specified by the user
        HashMap errors = new HashMap();
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        HashMap info = new HashMap();
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );

        //System.out.println("Action is = " + action);

        if( ("quarterPricing".equals(action)) || ( action==null ) || ( action.trim().length() == 0 ) )
        {
            subform.setProductId("");
            // Balaram on July 31, 2003
            try
            {
                ArrayList mktgParts = MarketingDAO.loadApprovedMarketingPartNumbers();
                mktgParts.add(0,new org.apache.struts.util.LabelValueBean("---- CHIP -----","0"));
                session.setAttribute( "mktgParts", mktgParts );
            }
            catch( Exception e )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_MARKETING_PART_NUMBERS );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_MARKETING_PART_NUMBERS );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }

            if(subform == null)
            {
                subform = new PricingForm();
            }

            subform.setPriceList(getPriceList());
            request.setAttribute("showList", "FALSE");
            if ("quarterPricing".equals(action))
            {
                return mapping.findForward("quarterPricing");
            }
            else
            {
                return (mapping.findForward("stndPricing"));
            }
        }
        else if(("customerPricing".equals(action)) || ("searchPricing".equals(action)))
        {
            subform.setProductId("");
            subform.setCustomerId(0);
            subform.setSample(1);

            if(subform == null)
            {
                subform = new PricingForm();
            }

            subform.setPriceList(getPriceList());

            // Balaram on July 31, 2003
            try
            {
                Object customerNames = CustomerDAO.getAllCustomerNames();
                request.setAttribute( "customers", customerNames );
                if(session.getAttribute("mktgParts") == null )
                {
                    ArrayList mktgParts = MarketingDAO.loadApprovedMarketingPartNumbers();
                    mktgParts.add(0,new org.apache.struts.util.LabelValueBean("---- CHIP -----","0"));
                    session.setAttribute( "mktgParts", mktgParts );
                }
            }
            catch( Exception e )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_ALL_CUSTOMER_NAMES );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_ALL_CUSTOMER_NAMES );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }

            request.setAttribute("showList", "FALSE");

            if(action.equals("customerPricing"))
            {
                return (mapping.findForward("customerPricing"));
            }
            else
            {
                return (mapping.findForward("loadPricing"));
            }
        }
        else if("UpdateStandardPricing".equals(action))
        {
            int productId = -1;
            int sample=-1;
            //??Change the names in the jsp and beans productId to marketingPartNo
            DBTransaction dbTransaction = null;
            boolean success = false;

            try
            {
                // Start transaction
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();

                String[] fromQty = subform.getFromQty();
                String[] toQty = subform.getToQty();
                String[] price = subform.getPrice();

                // Get product id
                try
                {
                    productId = Integer.parseInt( request.getParameter("productId") );
                }
                catch(Exception e )
                {
                    productId = -1;
                }
                sample = Integer.parseInt(request.getParameter( "sample" ) );
                //Update the price details..
                PricingDAO.saveStandardPricing( dbTransaction,
                                                 productId,
                                                 fromQty,
                                                 toQty,
                                                 price,
                                                 user,sample);

                success = true;
                info.put( "Pricing", "Details Saved Successfully" );
                subform.setSample(1);
            }
            catch (Exception e)
            {
                e.printStackTrace();

                // Balaram on July 31, 2003
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_UPDATING_PRODUCT_PRICING );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_UPDATING_PRODUCT_PRICING );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }
            finally
            {
                // Rollback or Commit the Transaction
                if (success == true)
                {
                    dbTransaction.commit();
                }
                else
                {
                    dbTransaction.rollback();
                }
            }

            request.setAttribute("showList", "FALSE");

            subform.setProductId("");
            subform.setSample(1);
            return (mapping.findForward("stndPricing"));
        }
        else if("UpdateCustomerPricing".equals(action))
        {
            //Commented for testing purpose
            int productId = -1;
            int customerId = subform.getCustomerId();
            int isSample = subform.getSample() ;

            DBTransaction dbTransaction = null;
            boolean success = false;

            try {
                // Start transaction
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();

                String[] fromQty = subform.getFromQty();
                String[] toQty = subform.getToQty();
                String[] price = subform.getPrice();
                //System.out.println("From Qty values " + fromQty.length + toQty.length);

                // Get product ID
                try
                {
                    productId = Integer.parseInt( request.getParameter("productId") );
                }
                catch(Exception e )
                {
                    productId = -1;
                }

                // Update the price details
                PricingDAO.saveCustomerPricing(dbTransaction,customerId, productId,
                                    fromQty,toQty,price,user, isSample);

                success = true;

                info.put( "Pricing", "Details Saved Successfully" );
            }
            catch( Exception e )
            {
                e.printStackTrace();

                // Balaram on July 31, 2003
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_UPDATING_CUSTOMER_PRICING );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_UPDATING_CUSTOMER_PRICING );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }
            finally
            {
                if (success == true)
                {
                    dbTransaction.commit();
                }
                else
                {
                    dbTransaction.rollback();
                }
            }

            request.setAttribute("showList", "FALSE");

            // Balaram on July 31, 2003
            try
            {
                Object customerNames = CustomerDAO.getAllCustomerNames();
                request.setAttribute( "customers", customerNames );
            }
            catch( Exception e )
            {
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_ALL_CUSTOMER_NAMES );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_ALL_CUSTOMER_NAMES );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }
            //added by varma(01 jul 2004)
            subform.setProductId("");
            subform.setCustomerId(0);
            subform.setSample(1);
            return (mapping.findForward("customerPricing"));
        }
        // Added by veeru on 1st August 2004
        else if("UpdateQuarterPricing".equals(action))
        {
            int productId = -1;
            int sample = -1;
            DBTransaction dbTransaction = null;
            boolean success = false;

            try {
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();

                try
                {
                    productId = Integer.parseInt( request.getParameter("productId") );
                }
                catch(Exception e )
                {
                    productId = -1;
                }
                int isSample = subform.getSample() ;
                PricingDAO.saveQuarterPricing(dbTransaction, productId, subform.getPeriodList(),user, isSample );
                success = true;

                info.put( "Pricing", "Details Saved Successfully" );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_UPDATING_QUARTER_PRICING );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_UPDATING_QUARTER_PRICING );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }
            finally
            {
                if (success == true)
                {
                    dbTransaction.commit();
                }
                else
                {
                    dbTransaction.rollback();
                }
            }
            request.setAttribute("showList", "FALSE");
            subform.setProductId("");
            subform.setSample(1);
            return mapping.findForward("quarterPricing");
        }
        else if("addRow".equalsIgnoreCase(action))
        {
            int periodNo = Integer.parseInt(request.getParameter("periodNo"));

            ArrayList periodList = subform.getPeriodList();
            Period period = ( Period )periodList.get( periodNo );

            ArrayList priceList = period.getPriceList();
            priceList.add(new Pricing());

            period.setPriceList( priceList );
            periodList.set(periodNo, period);
            subform.setPeriodList( periodList );
            request.setAttribute( "showList", "TRUE" );
            //subform.setProductId("");
            return mapping.findForward("quarterPricing");
        }
        else if(action.equals("loadQuarterPricing"))
        {
            try
            {
                int productId;

                try
                {
                    productId = Integer.parseInt( request.getParameter("productId") );
                }
                catch(Exception e )
                {
                    productId = -1;
                }

                int isSample = -1;
                if (request.getParameter("isSample") != null)
                {
                    isSample = Integer.parseInt(request.getParameter("isSample"));
                }
                else
                {
                    isSample = 1;
                }
                if(productId == -1)
                {
                    request.setAttribute( "showList", "FALSE" );
                    errors.put( "Product - " + request.getParameter("productId")," Please select a product to set the price" );
                }
                else
                {
                    HashMap hashmap = PricingDAO.getQuarterPricing(productId, isSample );
                    ArrayList periodList = (ArrayList)hashmap.get("list");
                    String    newList    =  (String)hashmap.get("newList");
                    subform.setPeriodList( periodList ) ;
                    if((periodList == null)||(periodList.size() == 0))
                    {
                        request.setAttribute("showList", "FALSE");
                        errors.put( "Quarters - " ," Quarters not set for the current year" );
                        String str= "/"+ConfigManager.getChipTracContext()+"/calendar.do?";
                        info.put ( "Calendar - ", "Click here to <a href='"+str+"'onmouseover=\"window.status='Click here to set Company Calender';return true\" onmouseout=\"window.status='';return true\"> generate </a>Quarters" );
                    }
                    else
                    {
                        if( "TRUE".equalsIgnoreCase(newList))
                        {
                            errors.put("Pricing Details", "Not Found for this product");
                            info.put("Please set the pricing details and update","");
                        }
                        request.setAttribute( "showList", "TRUE" );
                    }
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_PRICING_DETAILS );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_PRICING_DETAILS );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }
            //subform.setProductId("");
            return (mapping.findForward("quarterPricing"));
        }
        // End of Added by Veeru

        else if( ( "loadStndPricing".equals( action ) ) || ( "loadCustomerPricing".equals( action ) ) || ( "loadPricing".equals( action ) ) )
        {
            try
            {
                int productId;

                try
                {
                    productId = Integer.parseInt( request.getParameter("productId") );
                }
                catch(Exception e )
                {
                    productId = -1;
                }

                int customerId = -1;
                if (request.getParameter("customerId") != null)
                {
                    customerId = Integer.parseInt(request.getParameter("customerId"));
                }
                else
                {
                    customerId = 0;
                }
                int sample=-1;
                if (request.getParameter("sample") != null)
                {
                    sample = Integer.parseInt(request.getParameter("sample"));
                }
                else
                {
                    sample = 1;
                }
                ArrayList priceList = null;
                if(productId != -1 && customerId == 0)
                    priceList = PricingDAO.getStandardPricing(productId, sample );
                else if(productId != -1 && customerId != 0)
                    priceList = PricingDAO.getCustomerPricing(productId, customerId, sample);

                if(productId == -1)
                {
                    request.setAttribute( "showList", "FALSE" );
                    if("loadPricing".equals( action )){
                         errors.put( "Product" + request.getParameter("productId")," Please select a product to view the price details" );
                    }else{
                        errors.put( "Product" + request.getParameter("productId")," Please select a product to set the price" );
                    }
                }
                else
                {
                    request.setAttribute("showList", "TRUE");

                    if((priceList == null)||(priceList.size() == 0))
                    {
                        errors.put("Pricing Details", "Not Found for this product");
                        info.put("Please set the pricing details and update","");
                        request.setAttribute("showList", "FALSE");
                    }
                }

                subform.setCustomerName(CustomerDAO.loadCustomerName(customerId));

                subform.setPriceList(priceList);
                request.setAttribute( "customers", CustomerDAO.getAllCustomerNames() );
                request.setAttribute( "newList", getPriceList() );

                //Return to the specified page accorging to the input
                if( action.equals( "loadStndPricing" ) )
                {
                    if( productId == -1 )
                    {
                        request.setAttribute( "showList", "FALSE" );
                    }
                    else
                    {
                        request.setAttribute( "showList", "TRUE" );
                    }

                    return (mapping.findForward( "stndPricing" ) );

                }
                else if(action.equals("loadCustomerPricing"))
                {
                    if(customerId == 0)
                    {
                        errors.put("Customer" , "Please select the customer");
                        //Added by Krishna Prasad on 8th May 2004, as these message are unecessaryly displaying in the screen
                        if((priceList == null)||(priceList.size() == 0))
                        {
                            errors.remove("Pricing Details");
                            info.remove("Please set the pricing details and update");
                        }
                    }

                    if( ( productId == -1 ) || ( customerId == 0 ) )
                    {
                        request.setAttribute("showList", "FALSE");
                    }
                    else
                    {
                        request.setAttribute( "showList", "TRUE" );
                    }

                    return (mapping.findForward("customerPricing"));

                }
                else
                {
                    return (mapping.findForward("loadPricing"));
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_LOADING_PRICING_DETAILS );
                errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, ERROR_IN_LOADING_PRICING_DETAILS );
                session.setAttribute( SessionKeys.ERROR_REPORT, e );
            }
        }
        else if ( action.equals("uploadSetup") )
        {

            return mapping.findForward("uploadFile");
        }
        else if (action.equals("uploadFile") )
        {
            FormFile file = subform.getTheFile();
            String fileName= file.getFileName();
            try
            {
                fileLocation = ConfigManager.getPriceSetupPortingDirectory();

                AdaptorUtils.makeAllAdaptorDirs( fileLocation );

                try
                {
                    //To remove already Existed Files, IF Any
                    removeOldFiles();
                }
                catch(Exception e )
                {
                   errors.put("File is in use",null);
                }

                if( ( fileName != null ) && ( fileName.trim().length() != 0 ) )
                {
                    if( fileName.endsWith(".xls") )
                    {
                        fileName = "Pricing_" + AdaptorUtils.getTimeAsString()+".xls";

                        InputStream stream = file.getInputStream();
                        OutputStream bos = new FileOutputStream( fileLocation+"/"+fileName );
                        int bytesRead = 0;
                        byte[] buffer = new byte[8192];

                        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1)
                        {
                            bos.write(buffer, 0, bytesRead);
                        }

                        bos.close();
                        info.put("File uploaded successfully",null);
                    }
                    else
                    {
                        errors.put("Only Files in EXCEL format can be uploaded",null);
                    }
                }
            }
            catch(FileNotFoundException fnfe)
            {
                fnfe.printStackTrace();
                throw new ScalarException(" Specified file : "+fileName, fnfe);
            }
            catch(IOException ioe)
            {
                ioe.printStackTrace();
                throw new ScalarException(" Streaming is failed : "+fileName, ioe);
            }

            try
            {
               new PriceSetupParser().execute();
               info.put(" Pricing Details updated succesfully", null ); 
            }
            catch(Exception e )
            {
                errors.put("Could not update the pricing Details",null);
            }

            return mapping.findForward("uploadFile");
        }
        //Please look at this return later(Where do we need this retrurned) ????
        return ( mapping.findForward( "success" ) );
    }

    private static ArrayList getPriceList()
    {
        ArrayList priceList = new ArrayList();
        //Create Five as default
        for(int i=0; i<5; i++) {
             Pricing pricing = new Pricing();
             priceList.add(pricing);
        }

        return priceList;
    }

    private void removeOldFiles() throws Exception
    {
        try
        {
            AdaptorUtils.removeOldFiles( fileLocation, null );
        }
        catch ( ScalarException se )
        {
            System.out.println( "Exception occurred while deleting old files at Cost Codes uplaod file Directory" );
            throw se;
        }
    }

}
